<template>
    <div>
        <navigation-bar :customTitle="curTitle">
            <div class="searchContent">
                <custom-button type="add" style="margin-right: 10px" @addClick="addClick"></custom-button>
            </div>
        </navigation-bar>

        <div>
            <table-index
                :dataSource="dataSource"
                :tableColumns="tableColumns"
                :btnList="btnList"
                :pageSize="pageSize"
                :pageCount="pageCount"
                :pageNo="pageNo"
                @pageChange="pageChange"
                @editRow="editRow"
                @viewRow="viewRow"
                @deleteRow="deleteRow"
                selection
                @handleSelectionChange="handleSelectionChange"
                @relationUserRow="relationUserRow"
                @relationMenuRow="relationMenuRow"
                :showPage="false"
                :height="secondTableHeight"
                rowKey="ROLE_NAME"
            ></table-index>
        </div>

        <div v-if="dialogShow">
            <custom-dialog :title="dialogTitle" size="large" @dialogClose="dialogClose">
                <form-index :formConfig="formConfig" @submit="submit" :type="type" @formInputChange="formInputChange" ref="form">
                    <!--  <div>这里还可以插入其它内容进行拓展</div> -->
                </form-index>
            </custom-dialog>
        </div>

        <div v-if="dialogSelectUserShow">
            <custom-dialog title="选择用户" size="large" @dialogClose="dialogSelectUserShow = false">
                <SelectUser :userList="userList" @getData="getUserData"></SelectUser>
            </custom-dialog>
        </div>

        <div v-if="dialogSelectMenuBtnShow">
            <custom-dialog :title="relaMenuTitle" size="large" @dialogClose="closeRelaMenu">
                <SelectMenuBtn
                    :rolePower="rolePower"
                    :roleItem="roleItem"
                    @cancel="dialogSelectMenuBtnShow = false"
                    @onSave="dialogSelectMenuBtnShow = false"
                ></SelectMenuBtn>
            </custom-dialog>
        </div>
    </div>
</template>

<script>
import {roleManageForm} from '@/assets/form/managementCenter/systemManage/roleManage'
import customDialog from '@/components/customComponents/customDialog'
import SelectUser from '@/components/customComponents/managementCenter/SelectUser'
import SelectMenuBtn from '@/components/customComponents/managementCenter/SelectMenuBtn'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBar from '@/components/customComponents/managementCenter/navigationBarCustomTitle'
import {AjaxCommon} from '@/libs/apiCommon'
import {CardId} from '@/libs/cardId'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
export default {
    components: {
        navigationBar,
        customButton,
        tableIndex,
        customDialog,
        formIndex,
        SelectUser,
        SelectMenuBtn
    },
    data() {
        return {
            rolePower: [],
            roleItem: {},
            dialogSelectMenuBtnShow: false,
            dialogSelectUserShow: false,
            relaMenuTitle: '',
            optionValue: 'name',
            options: [
                {
                    value: 'name',
                    label: '登录名'
                },
                {
                    value: 'realname',
                    label: '真实姓名'
                }
            ],
            orgInfo: {},
            secondTableHeight: document.body.clientHeight - 170,
            selectOrgList: [],
            userName: null,
            status: '',
            curTitle: '角色管理',
            statusList: Utility.getDictList('status'),
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                //              {
                //   "ROLE_NAME": "sample string 1", // 角色名称
                //   "PARENT_ROLE_NAME": "sample string 2", // 父级角色名称
                //   "ROLE_DESC": "sample string 3", // 角色描述
                //   "IS_ENABLE": 4,  // 是否启用（0：不启用 1：启用）
                //   "MENUS_GUID": "sample string 5", // 菜单返回 中men的GUID及按钮操作集合（多个菜单ID用，分隔  菜单和按钮用$分隔）
                //   "USERS_USERID": "sample string 6", // 用户user_id集合（多个用户ID用，分隔）
                //   "SYS_GUIDS": "sample string 7" // 菜单返回中SYS的子系统ID 集合 （多个ID，分隔）
                // }
                // {
                //     type: 'selection',
                //     width: 60,
                //     align: 'center'
                // },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'ROLE_NAME',
                    title: '角色名称',
                    tree: true
                },
                {
                    key: 'PARENT_ROLE_NAME',
                    title: '父级角色名称'
                },
                {
                    key: 'ROLE_DESC',
                    title: '角色描述'
                    // slot: 'sex'
                },
                {
                    key: 'IS_ENABLE',
                    title: '是否启用',
                    slot: 'IS_ENABLE'
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 220,
                    align: 'center'
                }
            ],
            btnList: ['edit', 'relationUser', 'delete', 'relationMenu'],
            pageSize: 20,
            pageCount: 100,
            pageNo: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: null,
            type: 'add',
            userList: [],
            userInfo: {}
        }
    },
    created() {},
    methods: {
        closeRelaMenu() {
            let self = this
            PopupCommon.confirm('确定要关闭吗？关闭后当前编辑数据将丢失！')
                .then((result) => {
                    if (result) {
                        self.dialogSelectMenuBtnShow = false
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        },
        getUserData(uList) {
            let self = this
            let tempData = {}
            tempData.ROLE_NAME = this.userInfo.ROLE_NAME
            tempData.USERS_USERID = uList.map((t) => t.user_id).toString()
            AjaxCommon('/api/Role/EditRoleUser', 'post', tempData).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '编辑成功')
                    self.initPage()
                    self.dialogSelectUserShow = false
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        getOrgInfo(item) {
            this.orgInfo = item
            this.curTitle = item.fullName
            this.searchClick()
        },
        getHeight() {
            this.secondTableHeight = document.body.clientHeight - 170
        },
        customClick(isTrue) {
            this.useOrg(isTrue)
        },
        handleSelectionChange(d) {
            this.selectOrgList = d
        },
        // 关联菜单
        async relationMenuRow(d) {
            this.roleItem = d
            this.relaMenuTitle = `菜单配置【${d.ROLE_NAME}】`
            // 获取此角色下的菜单权限
            const rolePower = await AjaxCommon(`/api/role/GetMenuTree/${d.ROLE_NAME}`, 'get', null)
            const res = rolePower?.data?.Message ?? []
            this.rolePower = res
            this.dialogSelectMenuBtnShow = true
        },
        relationUserRow(d) {
            this.userInfo = d
            let self = this
            // 根据角色名获取角色下所有用户
            AjaxCommon(`/api/role/GetRoleUsers/${d.ROLE_NAME}/10000/1`, 'get', null).then((res) => {
                let userList = []
                if (res?.data?.Code == 200) {
                    userList = res.data.Message.rows
                }
                self.userList = userList
                self.dialogSelectUserShow = true
            })
        },
        formInputChange(e) {
            if (e.filedName == 'idCard') {
                const data = CardId.getInfoByCardId(e.value)
                if (data) {
                    let newData = e.allData
                    newData['birthday'] = data.birthday
                    newData['sex'] = data.sex
                    this.$refs.form.changeFormValue(newData)
                }
            }
        },
        submit(d) {
            console.log(d)
            let self = this
            d.IS_ENABLE = d.IS_ENABLE ? '1' : '0'
            if (d.ROLE_ID) {
                AjaxCommon('/api/Role/EditRole', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                delete d.ROLE_ID
                d.MENUS_GUID = ''
                d.USERS_USERID = ''
                d.SYS_GUIDS = ''
                // 根据类型调用不同接口
                let url = '/api/Role/AddRole'
                AjaxCommon(url, 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage()
                        self.dialogClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        resetClick() {
            this.userName = null
            this.searchClick()
        },
        addClick() {
            this.formConfig = roleManageForm(
                this.dataSource.filter((b) => b.PARENT_ROLE_NAME == '' || b.PARENT_ROLE_NAME == null),
                'add'
            )
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = ''
                    }
                })
            })
            this.formConfig = formConfigItem
            this.type = 'add'
            this.dialogTitle = '新增'
            this.dialogShow = true
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        async editRow(d) {
            this.formConfig = roleManageForm(
                this.dataSource.filter((b) => b.PARENT_ROLE_NAME == '' || b.PARENT_ROLE_NAME == null),
                'edit'
            )
            // 先获取组织机构的用户信息
            this.type = 'edit'
            let formConfigItem = this.formConfig
            console.log(formConfigItem, d, 'data.........')
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'ROLE_ID') {
                        t.filedValue = d['id']
                    } else if (t.fieldName == 'PARENT_ROLE_NAME') {
                        t.filedValue = d['PARENT_ROLE_NAME']
                    } else if (t.fieldName == 'ROLE_NAME') {
                        t.filedValue = d['ROLE_NAME']
                    } else if (t.fieldName == 'IS_ENABLE') {
                        t.filedValue = d['IS_ENABLE'] == 1
                    } else if (t.fieldName == 'ROLE_DESC') {
                        t.filedValue = d['ROLE_DESC']
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '编辑'
            this.dialogShow = true
        },
        viewRow(d) {
            this.type = 'look'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = d.data[t[res]]
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogTitle = '查看'
            this.dialogShow = true
        },
        // 启用或禁用组织机构 isTrue  true禁用 false 不禁用
        useOrg(isTrue) {
            const selectOrgList = this.selectOrgList
            if (selectOrgList.length < 1) {
                PopupCommon.notify('info', '请选择至少一个机构')
                return
            }
            const id = selectOrgList.map((t) => t.id).toString()
            let self = this
            let apiUrl = ''
            let tipMsg = ''
            if (isTrue) {
                apiUrl = `api/OrgSysManage/ChangeOrgsDisable`
                tipMsg = '禁用'
            } else {
                apiUrl = 'api/OrgSysManage/ChangeOrgsEnable'
                tipMsg = '启用'
            }
            AjaxCommon(apiUrl, 'post', {orgids: id}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', tipMsg + '成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },

        deleteRow(d) {
            const ROLE_NAME = d.ROLE_NAME
            let self = this
            AjaxCommon(`/api/role/Delete/${ROLE_NAME}`, 'post', {}).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '删除成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        // 初始化事件
        initPage() {
            let self = this
            let params = `/api/Role/GetRoleTreeData`
            AjaxCommon(params, 'get', null).then((res) => {
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    data?.map((t) => {
                        t?.children?.map((b) => {
                            b.PARENT_ROLE_NAME = t.ROLE_NAME
                            return b
                        })
                    })
                    self.formConfig = roleManageForm(
                        data.filter((b) => b.PARENT_ROLE_NAME == '' || b.PARENT_ROLE_NAME == null),
                        'add'
                    )
                    self.dataSource = data
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style></style>
